/*
 * vfile.cpp
 *
 *  Created on: Dec 22, 2013
 *      Author: elazar
 */

#include <sys/stat.h>
#include <unistd.h>
#include "dispatcher.h"
#include "vfile.h"

#include <iostream>
#include <vector>
#include <ctime>

string int_to_string(int num){
	std::stringstream ss;
	ss << num;
	return ss.str();
}

string get_time(string s) {
	time_t raw_time;
	struct tm* current_time;
	time(&raw_time);
	current_time = localtime(&raw_time);
	return asctime(current_time);
}

string Vfile::path = ".";

Vfile::Vfile(string filename, string owner):dir_name(filename){
	string st = Vfile::path + '/' + filename;
	mkdir(st.c_str(), S_IRWXU);
	owners.insert(owner);
}

void Vfile::add_owner(string name) {
	if (!owners.insert(name).second)
		throw IllegalAction(Error_ALREADY_OWNER, name);
}

void Vfile::remove_owner(string name) {
	if (!owners.erase(name))
		throw IllegalAction(Error_NOT_AN_OWNER, name);
}

bool Vfile::is_owner(string name) {
	return owners.count(name);
}

string Vfile::get_last_version(){
	return int_to_string(versions.size());
}
string Vfile::get_version_path(int version) {
	string version_string = int_to_string(version);
	string file_path = (Vfile::path+'/'+dir_name+'/'+version_string);
	return file_path;
}

string Vfile::get_last_version_path(){
	string last_version = int_to_string(versions.size());
	return string(Vfile::path +'/'+dir_name+'/'+last_version);
}

void Vfile::checkout(string name) {
	if (!lock_user.empty())
		throw IllegalAction(Error_ALREADY_CHECKED_OUT, lock_user);
	lock_user = name;
}

void Vfile::undo_checkout(string name) {
	if (lock_user != name)
		throw IllegalAction(Error_NOT_CHECKED_OUT, lock_user);
	lock_user.clear();
}

string Vfile::add_version_to_path(Version v) {
	if (this->versions.size() && lock_user != v.maker)
		throw IllegalAction(Error_NOT_CHECKED_OUT, lock_user);
	versions.push_back(v);

	std::stringstream file_path;
	file_path <<  Vfile::path << '/' << dir_name << '/' << versions.size()-1;
	return file_path.str();
}

void Vfile::unlock_user(){
	lock_user.clear();
}

bool Vfile::checked_out() {
	return !lock_user.empty();
}

bool Vfile::checked_out_by(string username) {
	return lock_user == username;
}

string Vfile::get_description() {
	std::stringstream ss;

	if (checked_out())
		ss << "checked out by: " << lock_user;
	else
		ss << "version no': " << versions.size();

	std::set<string>::iterator powner = owners.begin();
	ss << " (owners: " << *powner;
	while (++powner != owners.end())
		ss << ", " << *powner;
	ss << ")";


	return ss.str();
}

string Vfile::get_versions() {
	std::stringstream ss;
	int i=0;
	for (std::vector<Version>::iterator pv = versions.begin(); pv != versions.end(); ++pv)
		ss << "Ver. " << i++ << ": " << pv->info() << "\n";
	return ss.str();
}
